<?php

namespace App\Http\Controllers\Wx;

use App\Events\PaySuccessful;
use App\Notifications\NoticeDriver;
use App\Notifications\OrderPaid;
use App\Order;
use App\Sms\Contracts\Sms;
use App\SysConfig;
use Carbon\Carbon;
use DB;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Log;
use EasyWeChat\Payment\Order as WechatOrder;
use Notification;


class IndexController extends Controller
{
    public function index(Request $request) {

        $order = Order::with('driver')
            ->where('member_id',$this->member()->id)
            ->whereIn('status',[0,1,2])
            ->first();
        if(!$order)
            return view('wx.index');
        else if($order->status == 0) {
            return view('wx.index_0',['order'=>$order]);
        } else if($order->status == 1) {
            return view('wx.index_1',['order'=>$order]);
        } else if($order->status == 2) {
            return view('wx.index_2',['order'=>$order]);
        } else {
            return view('wx.index_err',['order'=>$order]);
        }


    }

    public function test(Sms $sms) {
        $rt  = $sms->sendSms('18788402136','关于元旦收假工作安排！');
        $arr = explode('/',$rt);
        dd($arr[0]);

    }

    public function order_detail(Request $request) {
        $order = Order::with('driver')
            ->where('member_id',$this->member()->id)
            ->find($request->input('order_id'));
        if(!$order) {
            return back()->withErrors('订单不存在！');
        }

        return view('wx.order_detail',['order'=>$order]);
    }

    public function save_order(Request $request,Sms $sms) {

        $member = $this->member();

        try {
            $order = Order::make($request->all());
            $order->code = Order::getNewOrderCode();
            $order->member_id = $this->member()->id;
            $order->save();

            $member->name=$request->input('name');
            $member->phone=$request->input('phone');
            $member->save();

            //发送 订单处理提醒给 调度人员
            $set_item = SysConfig::where('key','phone')->first();
            if($set_item && !empty($set_item->value) ){
                $sms->sendSms($set_item->value,"你有1张待出票订单{$order->code}，赶快去处理吧！");
            }

            return redirect()
                ->route('home')
                ->with('msg','正在出票，请稍候！');
        } catch (\Exception $e) {
            Log::error('出票失败！'.$e->getMessage());

            return back()->withErrors('出票失败！');
        }

    }

    /**
     * 测试模式的微信支付
     * @return bool|string
     */
    public function makeTestPay(Request $request) {
        info('发起模拟微信支付：收到回调通知！测试模式！！！！');
        if(!config('app.debug') || config('app.env') == 'production' ) {
            return '生成环境无法发起测试支付！';
        }
        // 查询订单
        $order_id = $request->input('order_id');
        $order = Order::find($order_id);
        if(!$order) {
            return back()->withErrors(['订单不存在！']);
        }

        if (!$order) { // 如果订单不存在
            return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }

        // 如果订单存在
        // 检查订单是否已经更新过支付状态
        if ($order->paid_at) { // 假设订单字段“支付时间”不为空代表已经支付
            return true; // 已经支付成功了就不再更新了
        }

        try {
            return DB::transaction(function() use($order) {

                // 不是已经支付状态则修改为已经支付状态
                $order->paid_at = Carbon::now(); // 更新支付时间为当前时间
                $order->status = 2;
                $order->save(); // 保存订单

                //支付成功，触发事件
                //event(new PaySuccessful($order));
                Notification::send($order->member,new OrderPaid($order));
                Notification::send($order->driver,new NoticeDriver($order));

                return redirect()->route('home')
                    ->with('msg','支付成功！');
            });
        } catch (\Exception $e) {
            Log::error('发起模拟微信支付：微信支付通知异常：'.$e->getMessage());
            return back()->withErrors('发起模拟微信支付,微信支付异常：'.$e->getMessage());
        }




    }

    public function pay(Request $request,Application $wechat) {
        $order = Order::find($request->input('order_id'));

        if(!$order || $order->status != 1) {
            return back()->withErrors('订单不存在或者状态错误！');
        }

        //jssdk
        $js = $wechat->js;
        //发起微信支付
        $payment = $wechat->payment;


        //订单金额
        if(env('WX_TEST_PAY')) {
            $total_fee = 1;     //测试模式支付1分
        } else {
            $total_fee = $order->amount*100;
        }

        $notify_url = config('wechat.payment.notify_url');
        info('支付回调地址：'.$notify_url);

        //创建微信订单
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => '优客出行订单',
            'detail'           => '优客出行订单',
            'out_trade_no'     => $order->code,
            'total_fee'        => $total_fee, // 单位：分
            'notify_url'       => $notify_url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->member()->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $wechat_order = new WechatOrder($attributes);

        $result = $payment->prepare($wechat_order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组



            $data = [
                'order'=>$order,
                'js'=>$js,
                'config'=>$config
            ];

            return view('wx.pay',$data);

        } else {
            Log::error('微信下单失败：'.var_export($result,true));
            return back()->withErrors('微信下单失败：'.$result['return_msg'].','.$result['err_code_des']);
        }

    }

    public function pay_callback(Application $wechat) {
        info('微信支付回调开始！');
        $response = $wechat->payment->handleNotify(function($notify, $successful){
            info('微信支付回调通知,订单号：'.$notify->out_trade_no);
            // 查询订单
            $order = Order::where('code',$notify->out_trade_no)->first();
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order->paid_at) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }

            // 用户是否支付成功
            if ($successful) {
                try {
                    DB::transaction(function() use($order) {

                        // 不是已经支付状态则修改为已经支付状态
                        $order->paid_at = Carbon::now(); // 更新支付时间为当前时间
                        $order->status = 2;
                        $order->save(); // 保存订单

                        //支付成功，触发事件
                        //event(new PaySuccessful($order));
                        Notification::send($order->member,new OrderPaid($order));
                        Notification::send($order->driver,new NoticeDriver($order));

                    });
                } catch (\Exception $e) {
                    Log::error('微信支付通知异常：'.$e->getMessage());
                }


            } else { // 用户支付失败
                $order->status = -2;
                $order->save(); // 保存订单
            }

            return true; // 返回处理完成

        });
        return $response;
    }

    public function cancel_order(Request $request) {
        $order = Order::find($request->input('order_id'));

        if(!$order || $order->status != 1) {
            return back()->withErrors('订单不存在或者状态错误！');
        }

        try {
            DB::beginTransaction();
            $order->status = -1;
            $order->save();

            $driver = $order->driver;
            $driver->free = $driver->free + 1;
            $driver->save();

            DB::commit();
            return redirect()->route('home')->with('msg','订单取消成功！');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withErrors('取消订单失败！'.$e->getMessage());
        }

    }

    public function vcode(Request $request,Sms $sms) {

        $this->validate($request,[
            'phone'=>'required',
        ],[
            'phone.required'=>'必须填写手机号',
        ]);

        $phone = $request->input('phone');
        $vcode = (string)random_int(1000,9999);
        session()->put('vcode',$vcode);

        $rt = $sms->sendSms($phone,"您的验证码为{$vcode},请于5分钟内正确输入，如非本人操作，请忽略此短信");
        if($rt) {
            return response()->json(['success'=>true]);
        } else {
            return response()->json(['success'=>false,'msg'=>'发送短信失败！'.$vcode]);
        }
    }


}
